package org.totoro.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.totoro.annotation.Cacheable;
import org.totoro.cglib.CglibTest;

import java.lang.reflect.Method;

/**
 * @author YHL
 * @version V1.0
 * @Description: bean 初始化
 * @date 2018-11-15
 */
@Component
public class BeanPostProcessorTest implements BeanPostProcessor {

    private final Logger LOGGER = LoggerFactory.getLogger(BeanPostProcessorTest.class);

    /**
     * 处理前
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        return bean;
    }

    /**
     * 处理后
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {


        LOGGER.info("className:{}", bean.getClass().getName());

        Class<?>[] interfaces = bean.getClass().getInterfaces();

        for (Class<?> anInterface : interfaces) {

            LOGGER.info("\t\t Interface:{}", anInterface.getName());
            Method[] methods = anInterface.getMethods();

            for (Method method : methods) {

                Cacheable annotation = method.getAnnotation(Cacheable.class);

                if (!ObjectUtils.isEmpty(annotation)) {
                    LOGGER.debug("find Cacheable annotation");

                    CglibTest cglibTest = new CglibTest();
                    Object proxyObject = cglibTest.getProxyObject(bean);

                    return proxyObject;
                }
            }


        }


        return bean;
    }
}
